package com.example.movie.repo

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.example.common.entity.BaseResponse
import com.example.common.entity.MovieVideoEntity
import com.example.movie.api.MovieServerApi

class MoviePagingSource constructor(private var apiMovieServerApi: MovieServerApi, private val typeId: Int = -1, private val pageSize: Int = 10): PagingSource<Int, MovieVideoEntity>() {

    /**
     * 获取每一页数据的唯一标识（类似页码）
     */
    override fun getRefreshKey(state: PagingState<Int, MovieVideoEntity>): Int? {
        return state.anchorPosition?.let {anchorPosition ->
            var anchorPage = state.closestPageToPosition(anchorPosition)
            anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
        }
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, MovieVideoEntity> {
        try {
            var pageIndex = params.key ?: 1 //默认从第一页加载数据
            val loadSize = params.loadSize //加载多少条数据
            var response: BaseResponse<List<MovieVideoEntity>> = if (typeId == -1){
                apiMovieServerApi.getRecommendMultiVideo(pageIndex, pageSize)
            } else {
                apiMovieServerApi.getMultiVideoByTypeId(typeId, pageIndex, pageSize)
            }

            //重新计算上一页和下一页Key
            val prePageKey: Int? = (pageIndex - 1).run {
                if (this == 0) null else this
            }
            val nextPageKey: Int? = when{
                loadSize > pageSize -> loadSize / pageSize + 1
                response.code == 200 -> pageIndex + 1 //请求成功后页码加一
                else -> null
            }

            //返回结果
            return LoadResult.Page(response.data, prePageKey, nextPageKey)
        }catch (e: Exception){
            e.printStackTrace()
            return LoadResult.Error(e)
        }

    }


}
